// 获取分类列表
const cate = document.querySelector('.cate');
// console.log(cate);
const cateBig = document.querySelector('.sk_more');
// console.log(cateBig);
const categories = cate.parentNode.parentNode;
// console.log(categories);

let xhr = new XMLHttpRequest();
xhr.open('get', 'http://localhost:8888/goods/category');
xhr.onload = () => {
    let res = JSON.parse(xhr.responseText);
    // console.log(res);

    let str = '<li class="active">全部</li>';
    res.list.forEach(item => {
        str += `<li>${item}</li>`
    })
    cate.innerHTML = str
}
xhr.send()

cateBig.addEventListener('mouseover', () => {
    categories.style.display = 'block'
})
cateBig.addEventListener('mouseout', () => {
    categories.style.display = 'none'
})







// 获取商品列表
const commodity = document.querySelector('.sk_bd')
const ul = commodity.children[0];
const pagination = document.querySelector('.pagination');
// console.log(ul);

let info = {
    current: 1,
    pagesize: 12,
    search: '',
    filter: '',
    saleType: 10,
    sortType: 'id',
    sortMethod: 'ASC',
    category: '',
}
getList()
// 根据请求刷新页面
async function getList() {
    let res = await pAjax({
        url : 'http://localhost:8888/goods/list',
        data : info,
        dataType : 'json'
    })
    let str = ``;
        console.log(res);
        res.list.forEach(item => {
            str += `
        <li class="sk_goods" data-id=${item.goods_id}>
                        <a href=""><img src="${item.img_big_logo}" alt=""></a>
                        <h5 class="sk_goods_title">${item.title}</h5>
                        <p class="sk_goods_price"><em>¥${item.current_price}</em> <del>￥${item.price}</del></p>
                        <div class="sk_goods_progress">
                            已售<i>${item.sale_type}</i>
                            <div class="bar">
                                <div class="bar_in"></div>
                            </div>
                            剩余<em>${item.goods_number}</em>件
                        </div>
                        <button class="sk_goods_buy" data-id=${item.goods_id}>加入购物车</button>
                    </li>
        `
        // console.log(123);
            ul.innerHTML = str
        });


        // 分页
        pagination.innerHTML = `
    <p>分页</p>
            <div>
                <span class="left${info.current === 1 ? 'disable' : ''}">&lt;</span>
                <span>${info.current} / ${res.total}</span>
                <span class="right${info.current === res.total ? 'disable' : ''}">&gt;</span>
            </div>
            <select>
                <option value="12">12</option>
                <option value="16">16</option>
                <option value="20">20</option>
                <option value="24">24</option>
            </select>
            <input type="text" value="${info.current}">
            <button  data-total=${res.total}>跳转</button>
    `
    console.log(ul.children.length);
    
// return ul.children.length
}
// p = getList();
// p.then(function (res) {
//     console.log(res);
// })
// console.log(p);


console.log(ul.children.length);
// 选中效果
cate.addEventListener('click',e=>{
    e = e || window.event;
    let target = e.target || e.srcElement;
    if( target.nodeName !== 'LI') return;
    for(i=0;i<cate.children.length;i++){
        cate.children[i].classList.remove('active');
    }
    target.classList.add('active');
    info.category = target.innerHTML === '全部' ? '' : target.innerHTML;
    info.current = 1;
    // console.log(info);
    getList()
})


// 筛选
let filter = document.querySelector('.filter')
filter.addEventListener('click',e=>{
    e = e || window.event;
    let target = e.target || e.srcElement;
    // console.log(target);
    for(i=0;i<filter.children.length;i++){
        filter.children[i].classList.remove('active');
    }
    target.classList.add('active');
    info.filter = target.dataset.type;
    info.current = 1;
    getList();
})


// 折扣
let sale = document.querySelector('.sale')
sale.addEventListener('click',e=>{
    e = e || window.event;
    let target = e.target || e.srcElement;
    // console.log(target);
    for(i=0;i<sale.children.length;i++){
        sale.children[i].classList.remove('active');
    }
    target.classList.add('active');
    info.saleType = target.dataset.type;
    info.current = 1;
    getList();
})


// 排序
let sort = document.querySelector('.sort')
sort.addEventListener('click',e=>{
    e = e || window.event;
    let target = e.target || e.srcElement;
    // console.log(target);
    for(i=0;i<sort.children.length;i++){
        sort.children[i].classList.remove('active');
    }
    target.classList.add('active');
    info.sortType = target.dataset.type;
    info.sortMethod = target.dataset.method;
    info.current = 1;
    getList();
})


// 搜索框
let search = document.querySelector('.search')
search.addEventListener('input',()=>{
    info.search = search.value.trim();
    info.current = 1;
    getList();
})



// 分页实现
pagination.addEventListener('click',e=>{
    e = e || window.event
    let target = e.target || e.srcElement
    if(target.className === 'right'){
        info.current++;
        getList()
    }
    if(target.className === 'left'){
        info.current--;
        getList()
    }
    if(target.nodeName === 'BUTTON'){
        let num = target.previousElementSibling.value-0;
        let total = target.dataset.total-0;
        if(!num) num = 1;
        if(num<1) num = 1;
        if(num > total) num = total
        info.current = num;
        getList();
    }
})


// 下拉框
pagination.addEventListener('change', e => {
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.nodeName === 'SELECT') {
        info.pagesize = target.value
        getList()
    }
})


console.log(ul);
// 点击商品详情
ul.addEventListener('click', e => {
    e = e || window.event
    try{e.preventDefault()} catch(err){e.returnValue = false};
    let target = e.target || e.srcElement
    console.log(target);
    if (target.nodeName === 'LI') {
        window.sessionStorage.setItem('goodsId', target.dataset.id)
        // 跳转详情页
        window.location.href = './detail.html'

    }
    if (target.nodeName === 'BUTTON') {
        // 加入购物车要保证已登录
    // console.log(123);
        addCart(target.dataset.id)
    }
})


//加入购物车
async function addCart(goodsId) {
    console.log(123);
    
    let id = window.localStorage.getItem('id')
    let token = window.localStorage.getItem('token')
    // 判断id和token
    if (!id || !token) {
        if (window.confirm('您还没有登录点取消留在本页面,点击确定去到登录页面')) {
            window.location.href = './login.html'
            return
        }
    }
    console.log(123);

    // 发送请求
    let res = await pAjax({
        url: 'http://localhost:8888/cart/add',
        method: 'post',
        data: { id, goodsId },
        dataType: 'json',
        headers: { authorization: token }
    })
    console.log(res);

    if (res.code !== 1) {
        if (window.confirm('您还没有登录点取消留在本页面,点击确定去到登录页面')) {
            window.location.href = './login.html'
            return
        }
    }
    var a = confirm("恭喜您添加成功,是否跳转购物车");
    if (a == true) window.location.href = './cart.html'

}




// // 瀑布流
// // let info = {
// //     current: 1,
// //     pagesize: 12,
// //     search: '',
// //     filter: '',
// //     saleType: 10,
// //     sortType: 'id',
// //     sortMethod: 'ASC',
// //     category: '',
// // }

  let btn = document.querySelector('.btn');
  console.log(commodity,btn);

 
 async function getWaterfall(current) {
    info.current = current;
    let res = await pAjax({
        url : 'http://localhost:8888/goods/list',
        data : info,
        dataType : 'json'
    })
    btn.innerHTML = '正在加载中……'
    
setTimeout(() => {
    let str = ``;
        console.log(res);
        res.list.forEach(item => {
            str += `
        <li class="sk_goods" data-id=${item.goods_id}>
                        <a href=""><img src="${item.img_big_logo}" alt=""></a>
                        <h5 class="sk_goods_title">${item.title}</h5>
                        <p class="sk_goods_price"><em>¥${item.current_price}</em> <del>￥${item.price}</del></p>
                        <div class="sk_goods_progress">
                            已售<i>${item.sale_type}</i>
                            <div class="bar">
                                <div class="bar_in"></div>
                            </div>
                            剩余<em>${item.goods_number}</em>件
                        </div>
                        <button class="sk_goods_buy" data-id=${item.goods_id}>加入购物车</button>
                    </li>
        `
        // console.log(123);
        });
        ul.innerHTML += str
        btn.innerHTML = '加载更多'

}, 1000);


}
// console.log(ul.children.length);


  //  加载更多
  let current = 1
  btn.onclick = loadMore;
  function loadMore() {
    // if (btn.classList.contains('loading')) return;

    getWaterfall(++current);
  }
  console.log(ul.length);
  /******懒加载的实现*******/
  console.log(ul.children);
  let lis = ul.children;
  console.log(lis);
  console.log(lis.length);
  console.log(lis[lis.length - 1]);
//   window.onscroll = function () {
//     let sTop = document.documentElement.scrollTop;
//     let imgH = lis[lis.length - 1].offsetTop;
//     let contH = document.documentElement.clientHeight;
//     console.log(sTop, imgH, contH);
//     // 判断三者之间的结果
//     if (contH < (imgH + sTop)) {
//       btn.onclick();
//     }
//   }